<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/17
 * Time: 9:28
 */

namespace App\Http\Controllers\Applet;


use App\Http\Controllers\Controller;
use App\Models\AppletActivity;
use App\Models\AppletActivityUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ActivityUserController extends Controller
{
    /**
     * 获取个人信息 get
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function index(Request $request){
        $user_id = (int)$request->get('userid','');
        $info = AppletActivityUser::where('userid',$user_id)->get();
        if(!$info->isEmpty()){
            return $this->returnJson(0,'获取个人信息成功',$info);
        }
        return $this->returnJson(1,'获取个人信息失败');
    }

    /**
     * 获取活动参与人员信息 get
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function info(Request $request){
        $activity_id = (int)$request->get('activity_id','');
        $info = AppletActivityUser::where('activity_id',$activity_id)->get();
        if(!$info->isEmpty()){
            return $this->returnJson(0,'参与活动人员信息',$info);
        }
        return $this->returnJson(1,'该活动暂无参与人员');
    }

    /**
     * 参与活动报名 post
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function active(Request $request){
        $data = $request->all();
        if(!isset($data['activity_id']) or !isset($data['userid'])){
            return $this->returnJson(1,'缺少必要参数');
        }
        if((int)$data['activity_id'] == 0 or (int)$data['userid'] == 0){
            return $this->returnJson(1,'参数错误');
        }
        $password = AppletActivity::where('id',$data['activity_id'])->get('password','');
        if(!isset($data['password'])){
            $data['password'] = '';
        }
        if($data['password'] != $password){
            return $this->returnJson(1,'口令错误');
        }
        $info = AppletActivityUser::where('activity_id',$data['activity_id'])
            ->where('userid',$data['userid'])
            ->first();
        if(empty($info)){
            DB::beginTransaction();
            try{
                AppletActivity::where('id',$data['activity_id'])->increment('user_num',1);
                AppletActivityUser::insertGetId(['activity_id'=>$data['activity_id'],'userid'=>$data['userid']]);
                DB::commit();
                return $this->returnJson(0,'活动报名成功');
            }catch (\Exception $exception){
                Log::error($exception);
                DB::rollback();//事务回滚
                return $this->returnJson(1,'系统繁忙');
            }
        }
        return $this->returnJson(1,'已成功参与活动');
    }
}